package com.tff.gmall.passport.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.tff.gmall.beans.UmsMember;
import com.tff.gmall.service.UmsMemberService;
import com.tff.gmall.util.JwtUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Fafa Tuo
 * @version 1.0
 * @date 2021/7/9 14:54
 */
@Controller
public class PassportControllrt {

    @Reference
    private UmsMemberService umsMemberService;

    @RequestMapping(value = "/verify")
    @ResponseBody
    public String verify(String token,String currentIp){
        System.out.println("token===="+token);

        Map<String,String> map = new HashMap<>();
        //通过JWT验证真假，返回用户信息
        Map<String, Object> jwtMap = JwtUtil.decode(token, "gmall2020JWT",currentIp);
        if(jwtMap != null) {
            map.put("status","success");
            map.put("memberId",(String)jwtMap.get("memberId"));
            map.put("nickname",(String)jwtMap.get("nickname"));
        }else {
            map.put("status","fail");
        }

        return JSON.toJSONString(map);
    }

    /***
     * 登录验证
     * @param umsMember
     * @return
     */
    @RequestMapping(value = "/login")
    @ResponseBody
    public String login(UmsMember umsMember, HttpServletRequest request){
        String token = "";
        UmsMember loginUmsMember = umsMemberService.loginCheck(umsMember);
        //验证用户信息
        if(loginUmsMember != null){
            //登录成功
            //用JWT制作token
            Map<String,Object> map = new HashMap<>();
            map.put("memberId",loginUmsMember.getId());
            map.put("nickname",loginUmsMember.getNickname());

            String ip = request.getHeader("x-forwarded-for");   //从nginx转发中获取客户端的ip
            if (StringUtils.isBlank(ip)){
                ip = request.getRemoteAddr();   //从request请求中获取ip
                if(StringUtils.isBlank(ip)){
                    //理论上来讲应该做异常处理
                    ip = "127.0.0.1";
                }
            }
            //生产环境中这些值都要加密
            token = JwtUtil.encode("gmall2020JWT", map, ip);

            //存入redis一份
            umsMemberService.addUserToken(loginUmsMember.getId(),token);
        }else {
            //登录失败
            token = "fail";

        }
        return token;
    }

    @RequestMapping(value = "/index")
    public String index(String ReturnUrl, ModelMap modelMap){
        String returnUrl = ReturnUrl;
        System.out.println("returnUrl = " + returnUrl);
        modelMap.put("ReturnUrl",returnUrl);
        return "index";
    }

}
